﻿using Microsoft.SharePoint;
using NewsGator.Social;
using NewsGator.Social.Data.LinkPreview;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace NGPT.ApproveIt
{
    /// <summary>
    /// Implement approval logic using the NewsGator server side API.
    /// </summary>
    public class ApprovalService : IApprovalService
    {
        /// <summary>
        /// Create an approval activity in the Socila Sites activity stream.
        /// </summary>
        /// <param name="approverLogin">Login name of approver in DOMAIN\login format.</param>
        /// <param name="requestText">Request text.</param>
        /// <param name="objectUrl">URL of list item to be approved.</param>
        private void SubmitRequest(string approverLogin, string requestText, string objectUrl)
        {
            #region Parameters validation

            var userProfilemanager = new SocialProfileManager();
            var userProfile = userProfilemanager.GetUserProfile(approverLogin);
            if (userProfile == null)
            {
                throw new ArgumentException(string.Format("User {0} doesn't have a profile in SharePoint. A request can be sent only to a user who has profile.", approverLogin));
            }

            if (string.IsNullOrEmpty(requestText))
            {
                throw new ArgumentException("Request text cannot be empty.");
            }

            Uri uri;
            if (!(Uri.TryCreate(objectUrl, UriKind.Absolute, out uri)
                && (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps)))
            {
                throw new ArgumentException(string.Format("{0} value is not valid URL.", objectUrl));
            }

            #endregion

            string messageText;
            if (!string.IsNullOrEmpty(objectUrl))
            {
                messageText = string.Format("@({0}) {1} [url]{2}[/url] #requiresapproval", userProfile.Name, requestText, objectUrl);
            }
            else
            {
                messageText = string.Format("@({0}) {1} #requiresapproval", userProfile.Name, requestText);
            }

            var fm = new ActivityFeedWriter();
            fm.CreateDirectMessage(messageText);
        }

        public void RequestApproval(string approverLogin, string requestText, string siteUrl, Guid listId, int itemId)
        {
            string objectUrl = null;

            using (SPSite site = new SPSite(siteUrl))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPList list = web.Lists[listId];
                    if (list != null)
                    {
                        SPListItem item = list.GetItemById(itemId);

                        if (item != null)
                        {
                            if (item.File != null)
                            {
                                objectUrl = string.Format("{0}/{1}", item.ParentList.ParentWeb.Url, item.File.Url);
                            }
                            else
                            {
                                objectUrl = string.Format("{0}/{1}?ID={2}", item.ParentList.ParentWeb.Url, item.ParentList.Forms[PAGETYPE.PAGE_DISPLAYFORM].Url, item.ID);
                            }

                            this.SubmitRequest(approverLogin, requestText, objectUrl);
                        }
                        else
                        {
                            throw new Exception(string.Format("Item {0} not found in the list {1}.", itemId, listId.ToString()));
                        }
                    }
                    else
                    {
                        throw new Exception(string.Format("List {0} not found in the site {1}.", listId.ToString(), siteUrl));
                    }

                }
            }
        }
    }
}
